package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.leaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.CodeUtil;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate redis;
    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public void getCode(String phone) {
//      随机生成的验证码
        String code = CodeUtil.getRandomCode(6);
//      保存在redis内的key
        String key = RedisConstant.APP_LOGIN_PREFIX+phone;
        Boolean b = redis.hasKey(key);
        if (b){
            Long ttl = redis.getExpire(key,TimeUnit.SECONDS);
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC- ttl <RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                throw new leaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        smsService.sendCode(phone,code);
        redis.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }

    @Override
    public String login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
//    - 首先校验`phone`和`code`是否为空，若为空，直接响应`手机号码为空`或者`验证码为空`，若不为空则进入下步判断。
        if (phone ==null){
            throw new leaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (code==null){
            throw new leaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
//    - 根据`phone`从Redis中查询之前保存的验证码，若查询结果为空，则直接响应`验证码已过期` ，若不为空则进入下一步判断。
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        String value = redis.opsForValue().get(key);
        if (value==null){
            throw new leaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
//    - 比较前端发送的验证码和从Redis中查询出的验证码，若不同，则直接响应`验证码错误`，若相同则进入下一步判断。
        if (!code.equals(value)){
            throw new leaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
//    - 使用`phone`从数据库中查询用户信息，若查询结果为空，则创建新用户，并将用户保存至数据库，然后进入下一步判断。
//    - 判断用户是否被禁用，若被禁，则直接响应`账号被禁用`，否则进入下一步。
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone,phone);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        if (userInfo==null){
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setNickname("用户-"+phone.substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoMapper.insert(userInfo);
        }else if (userInfo.getStatus().equals(BaseStatus.DISABLE)){
            throw new leaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

//    - 创建JWT并响应给前端。
        return JwtUtil.getToken(userInfo.getId(),userInfo.getPhone());
    }

    @Override
    public UserInfoVo getLoginUserById(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        return new UserInfoVo(userInfo.getNickname(),null);
    }
}
